/***************************************************************************
 *   Copyright (C) 2008 by BogDan Vatra                                    *
 *   bogdan@licentia.eu                                                    *
 *                                                                         *
 *   This program is free software: you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation, either version 3 of the License, or     *
 *   (at your option) any later version.                                   *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>. *
 ***************************************************************************/
#include <QKeyEvent>
#include "query.h"
#include "lineedit.h"

using namespace SQL;

LineEdit::LineEdit(QWidget *parent)
		: QLineEdit(parent),m_query(0),m_handleFocus(true),m_useDoubleValidator(false),m_decimals(4), m_minValue(0), m_maxValue(0),m_doubleValidator(0)
{
	connect(this,SIGNAL(editingFinished()),SLOT(bindValue()));
}

LineEdit::~LineEdit()
{
}

bool LineEdit::handleFocus()
{
	return m_handleFocus;
}

void LineEdit::setHandleFocus(bool handleFocus)
{
	m_handleFocus=handleFocus;
}

const QString & LineEdit::queryName()
{
	return m_queryName;
}

void LineEdit::setQueryName(const QString & queryName)
{
	m_queryName = queryName;
	m_query = defaultDatabase()->query(m_queryName);

	if (!m_query)
		return;
	connect(m_query, SIGNAL(recordChanged(const QSqlRecord&)), SLOT(recordChanged(const QSqlRecord&)));
	connect(m_query, SIGNAL(beforeInsert()), SLOT(setReadWrite()));
	connect(m_query, SIGNAL(beforeUpdate()), SLOT(setReadWrite()));
	connect(m_query, SIGNAL(afterSelect()), SLOT(setReadOnly()));
	connect(m_query, SIGNAL(afterClose()), SLOT(setReadOnly()));
	connect(m_query, SIGNAL(afterPost()), SLOT(setReadOnly()));
	connect(m_query, SIGNAL(afterCancel()), SLOT(setReadOnly()));
	setDisabled(m_query->state() == Query::Select);
	if (m_fieldName.length())
		setFieldName(m_fieldName);
}

const QString & LineEdit::fieldName()
{
	return m_fieldName;
}

void LineEdit::setFieldName(const QString & fieldName)
{
	m_fieldName = fieldName;
	if (m_query)
	{
		setText(m_query->value(m_fieldName).toString());
		setAlignment(Query::typeIsNumber(m_query->value(m_fieldName).type()) ? Qt::AlignRight : Qt::AlignLeft);
	}
}

void LineEdit::setReadWrite()
{
	setEnabled(true);
	if (!m_query || !m_fieldName.length())
		return;
	if (m_query->state()==Query::Insert)
	{
		if (m_defaultValue.length())
			setText( m_defaultValue );
		else
			clear();
	}
	m_query->setValue(m_fieldName,text());
}

void LineEdit::setupValidator()
{
	if (!m_useDoubleValidator)
	{
		setValidator(0);
		return;
	}
	if (!m_doubleValidator)
		m_doubleValidator= new QDoubleValidator(this);
	int minval=m_minValue;
	if (m_query && m_minValueFieldName.length())
		minval=m_query->value(m_minValueFieldName).toInt();

	int maxval=m_maxValue;
	if (m_query && m_maxValueFieldName.length())
		maxval=m_query->value(m_maxValueFieldName).toInt();

	m_doubleValidator->setBottom(minval);
	m_doubleValidator->setTop(maxval);
	m_doubleValidator->setDecimals(m_decimals);

	setValidator(m_doubleValidator);
}

void LineEdit::focusInEvent(QFocusEvent * event)
{
	setupValidator();
	if (m_query && m_query->state() == Query::Update)
	{
		setCursorPosition(0);
		selectAll();
	}
	QLineEdit::focusInEvent(event);
	if (event->isAccepted())
		emit(focusIn());
}

bool LineEdit::useDoubleValidator()
{
	return m_useDoubleValidator;
}
void LineEdit::setUseDoubleValidator(bool useDoubleValidator)
{
	m_useDoubleValidator=useDoubleValidator;
}

int LineEdit::decimals()
{
	return m_decimals;
}
void LineEdit::setDecimals(int decimals)
{
	m_decimals=decimals;
}

double LineEdit::minValue()
{
	return m_minValue;
}
void LineEdit::setMinValue(double m_minValue)
{
	m_minValue=m_minValue;
}

QString LineEdit::minValueFieldName()
{
	return m_minValueFieldName;
}
void LineEdit::setMinValueFieldName(const QString & minValueFieldName)
{
	m_minValueFieldName=minValueFieldName;
}

double LineEdit::maxValue()
{
	return m_maxValue;
}
void LineEdit::setMaxValue(double maxValue)
{
	m_maxValue=maxValue;
}

QString LineEdit::maxValueFieldName()
{
	return m_maxValueFieldName;
}
void LineEdit::setMaxValueFieldName(const QString & maxValueFieldName)
{
	m_maxValueFieldName=maxValueFieldName;
}

QString LineEdit::defaultValue()
{
	return m_defaultValue;
}
void LineEdit::setDefaultValue(const QString & defaultValue)
{
	m_defaultValue=defaultValue;
}

void LineEdit::focusOutEvent(QFocusEvent * event)
{
	QLineEdit::focusOutEvent(event);
	if (event->isAccepted())
		emit(focusOut());
}

void LineEdit::setReadOnly()
{
	setDisabled(true);
	setAlignment(Query::typeIsNumber(m_query->value(m_fieldName).type()) ? Qt::AlignRight : Qt::AlignLeft);
	if (!m_query || !m_fieldName.length())
		return;
	if (m_query->state()==Query::Select)
		setText(m_query->value(m_fieldName).toString());
}

void LineEdit::recordChanged(const QSqlRecord& record)
{
	setupValidator();
	setText(record.value(m_fieldName).toString());
}

void LineEdit::bindValue()
{
	if (!m_query || !m_fieldName.length())
		return;
	m_query->setValue(m_fieldName,text().length()?text():QVariant());
}

void LineEdit::keyPressEvent(QKeyEvent * event)
{
	if (event->key()==Qt::Key_Escape)
	{
		if (m_handleFocus)
			 focusPreviousChild();
		emit(escapePressed());
	}
	if (event->key()==Qt::Key_Return || event->key()==Qt::Key_Enter)
	{
		bindValue();
		if (m_handleFocus)
			focusNextChild();
	}
	QLineEdit::keyPressEvent(event);
}
